package BackTracking.combination;

import java.util.*;

class threeSum {

    /**
     * 回溯加set<string>去重.超时
     *
     * @param nums the nums
     * @return the list
     */
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        int len = nums.length;
        Arrays.sort(nums);
        Set<String> set = new HashSet<>();
        dfs(nums,len,0,0,res, list, set);

        return res;



    }
    static void dfs(int[] nums, int len, int start, int sum, List<List<Integer>> res, List<Integer> list, Set<String> set){

        if(list.size()>3){
            return;
        }

        if(list.size()==3&&sum==0){
            String str ="";
            for (int i: list
            ) {
                str+=i;
            }
            if(set.add(str)){
                res.add(new ArrayList<>(list));
            }
            return;
        }

        for (int i = start; i < len; i++) {
            int num = nums[i];
            list.add(num);
            //节点的起点不能重复
            dfs(nums,len,i+1,sum+=num,res, list,set);
            sum-= list.get(list.size()-1);
            list.remove(list.size()-1);
        }

    }

    public static void main(String[] args) {
        int[] nums = new int[]{-1,0,1,2,-1,-4};
        for (List<Integer> res: threeSum(nums)
             ) {
            System.out.println(res);
        };
    }
}
